package com.LostAndFound.dao;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.LostAndFound.utils.DataSourceUtils;

public class SuccessRecordListDao {
	QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
	// 得到记录总条数
	public int getTotalRecordForEasyUI(String cid, String whatFlag) throws SQLException {
		String sql = "select count(*) from article where foundflag = 0 and invalidflag = 1";
		Long total = 0L;
		// 拼接分类
		if("all".equals(cid) && "all".equals(whatFlag)) {
			sql = sql+" ";
			total = (Long) runner.query(sql, new ScalarHandler());
		}else if("all".equals(cid) && !"all".equals(whatFlag)){
			sql = sql + " and whatflag = ? ";
			total = (Long) runner.query(sql, new ScalarHandler(),whatFlag);
		}else if(!"all".equals(cid) && "all".equals(whatFlag)) {
			sql = sql + " and cid = ? ";
			total = (Long) runner.query(sql, new ScalarHandler(),cid);
		}else if(!"all".equals(cid) && !"all".equals(whatFlag)) {
			sql = sql + " and cid = ? and whatflag = ?";
			total = (Long) runner.query(sql, new ScalarHandler(),cid,whatFlag);
		}
		return total.intValue();
	}
	// 根据条件得到记录
	public List<Map<String, Object>> findAllSuccessRecordsForEasyUI(int startIndex, int pageSize, String cid,
			String whatFlag) throws SQLException {
		String sql = "select a.*, c.cname, f.foundid, f.foundtime, f.foundinfo "
				+ " from article a, category c, foundarticle f "
				+ " where foundflag = 0 and invalidflag = 1 "
				+ " and a.cid=c.cid and a.aid=f.aid ";
		List<Map<String, Object>> mapList = null;
		// 拼接分类
		if("all".equals(cid) && "all".equals(whatFlag)) {
			sql = sql+" order by f.foundtime desc limit ?,? ";
			mapList = runner.query(sql, new MapListHandler(),startIndex,pageSize);
		}else if("all".equals(cid) && !"all".equals(whatFlag)){
			sql = sql + " and whatflag = ? order by a.issuetime desc limit ?,? ";
			mapList = runner.query(sql, new MapListHandler(),whatFlag,startIndex,pageSize);
		}else if(!"all".equals(cid) && "all".equals(whatFlag)) {
			sql = sql + " and a.cid = ? order by f.foundtime desc limit ?,? ";
			mapList = runner.query(sql, new MapListHandler(),cid,startIndex,pageSize);
		}else if(!"all".equals(cid) && !"all".equals(whatFlag)) {
			sql = sql + " and a.cid = ? and whatflag = ? order by f.foundtime desc limit ?,? ";
			mapList = runner.query(sql, new MapListHandler(),cid,whatFlag,startIndex,pageSize);
		}
		return mapList;
	}
	// 删除foundArticle的记录
	public void handleDeleteAtFoundArticleForEasyUI(String aid) throws SQLException {
		String sql = "delete from foundarticle where aid = ?";
		runner.update(sql,aid);
	}
	// 删除article的记录
	public void handleDeleteAtArticleForEasyUI(String aid) throws SQLException {
		String sql = "delete from article where aid = ?";
		runner.update(sql, aid);
	}
}
